import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import LoginVue from "@/views/login/index.vue";
import HomeVue from "@/views/home/index.vue";
import { userInfoApi } from "@/http/api";
import { useUserStore } from "@/store/user";
import { ElMessage } from "element-plus";
const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: LoginVue,
  },
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/",
    component: () => import("../views/home/index.vue"),
    children: [
      {
        path: "index",
        component: () => import("../views/index/index.vue"),
      },
    ],
  },
  // {
  //   path: "/ums",
  //   component: ()=>import('../views/home/index.vue'),
  //   children:[{
  //     path:"admin",
  //     component:LoginVue
  //   }]
  // },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

// 路由守卫，进入请求
router.beforeEach((to, from, next) => {
  console.log(router.getRoutes);

  const store = useUserStore();
  let token = localStorage.getItem("token");
  if (store.menus.length === 0 && token) {
    userInfoApi().then((res) => {
      if (res.code === 200) {
        // 存数据到仓库
        store.menus = res.data.menus;
        store.username = res.data.username;
        // 动态路由
        store.routes.forEach((p) => {
          const route: RouteRecordRaw = {
            path: "/" + p.name,
            name: p.name,
            component: () => import("../views/home/index.vue"),
            // 通过路由拿到中文放在面包屑上
            meta: {
              title: p.title,
            },

            children: p.children.map((item) => ({
              path: item.name,
              name: item.name,
              component: () => import(`../views/${p.name}/${item.name}.vue`),
              meta: {
                title: item.title,
              },
            })),
          };

          if (route.children[0]) {
            // 访问父的时候重定向到第一个子路由
            route.redirect = `/${p.name}/${p.children[0]?.name}`;
          }

          router.addRoute(route);
        });
        next(to.fullPath);
      }
    });
  } else if (!token && to.path !== "/login") {
    // 判断是否存在token，没token禁止访问除登录之外其他页面
    ElMessage.error("请先登录");
    next("/login");
  } else if (token && store.menus.length !== 0 && to.path === "/login") {
    ElMessage.warning("请勿重复登录");
    next(from.fullPath);
  } else {
    next();
  }
});

export default router;
